﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ImageAppDataModels;
using BrainTechLLC;
using BrainTechLLC.WPF;
using BrainTechLLC.ThreadSafeObjects;
using ImageAppViewModels;
using System;
using DragDropLibrary;
using System.Windows.Controls.Primitives;
using DirectoryViewModels;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for DirectoryCollectionsViewControl.xaml
    /// </summary>
    public partial class DirectoryCollectionsViewControl : UserControl
    {
        public static readonly DependencyProperty DirectoriesToExamineCollectionViewModelProperty =
            DependencyProperty.Register("DirectoriesToExamineCollectionViewModel", typeof(DirectoriesToExamineCollectionViewModel), typeof(DirectoryCollectionsViewControl), new PropertyMetadata(null, OnDirectoriesToExamineCollectionViewModelPropertyChanged));

        public DirectoriesToExamineCollectionViewModel DirectoriesToExamineCollectionViewModel
        {
            get { return (DirectoriesToExamineCollectionViewModel)GetValue(DirectoriesToExamineCollectionViewModelProperty); }
            set { SetValue(DirectoriesToExamineCollectionViewModelProperty, value); }
        }

        private static void OnDirectoriesToExamineCollectionViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DirectoryCollectionsViewControl source = d as DirectoryCollectionsViewControl;
            DirectoriesToExamineCollectionViewModel vNew = e.NewValue as DirectoriesToExamineCollectionViewModel;
            DirectoriesToExamineCollectionViewModel vOld = e.OldValue as DirectoriesToExamineCollectionViewModel;
            source.UpdateDirectoriesToExamineCollectionViewModel(vNew, vOld);
        }

        private void UpdateDirectoriesToExamineCollectionViewModel(DirectoriesToExamineCollectionViewModel viewModel, DirectoriesToExamineCollectionViewModel viewModelOld)
        {
            DirectoriesToExamineCollectionViewModel = viewModel;

            // Let the UI bind to the view-model.
            this.DataContext = DirectoriesToExamineCollectionViewModel;
        }

        public DirectoryCollectionsViewControl()
        {
            InitializeComponent();
        }

        private void subGrid_Loaded(object sender, RoutedEventArgs e)
        {
            BrainTechLLC.WPF.TempExten.StretchListBox(sender as Grid);
        }

        private void txtNewGroupName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                CreateNewGroup();
            }
            else if (e.Key == System.Windows.Input.Key.Escape)
            {
                btnAddGroup.IsChecked = false;
            }
        }

        private void btnCreateNewGroup_Click(object sender, RoutedEventArgs e)
        {
            CreateNewGroup();
        }

        private void CreateNewGroup()
        {
            string groupName = txtNewGroupName.Text;
            if (string.IsNullOrEmpty(groupName))
            {
                btnAddGroup.IsChecked = false;
                return;
            }
            var found = DirectoriesToExamineCollectionViewModel.FindName(groupName);

            if (found != null)
            {
                MessageBox.Show("That directory group name already exists");
                return;
            }

            DirectoriesToExamineCollectionViewModel.AddOrFindGroup(groupName);
            btnAddGroup.IsChecked = false;
        }

        //public void DropOntoImageCollectionView(DropEventArgs<object> e)
        //{
        //    if (e.DroppedOnto == this || e.DroppedOnto == lstGroups)
        //    {
        //        if (DragAndDrop.GetRegisterDropTargetName(e.DroppedOnto) == "GroupView")
        //        {
        //            if (DragAndDrop.GetRegisterDragSourceName(e.DragSource) == "ImageCollectionView")
        //            {
        //                ListBox listBox = e.DragSource as ListBox;
        //                FileImageViewModel vmSingleSource = e.Object as FileImageViewModel;
        //                if (vmSingleSource == null)
        //                {
        //                    return;
        //                }

        //                foreach (FileImageViewModel vmSource in listBox.SelectedItems)
        //                {
        //                    var item = this.lstGroups.InputHitTest(e.DropPoint);

        //                    System.Windows.Controls.TextBlock tb = item as System.Windows.Controls.TextBlock;

        //                    if (tb == null)
        //                    {
        //                        var fe = BrainTechLLC.WPF.TempExten.GetAllChildren<TextBlock>(item as FrameworkElement, true);
        //                        if (fe != null && fe.Count > 0)
        //                        {
        //                            tb = fe[0];
        //                        }
        //                    }

        //                    if (tb != null)
        //                    {
        //                        GroupViewModel vmDest = tb.Tag as GroupViewModel;

        //                        if (vmDest != null)
        //                        {
        //                            DirectoriesToExamineCollectionViewModel.AddFileImageToGroup(vmSource.FileName, vmDest.GroupName);
        //                        }
        //                    }
        //                }
        //                //FileImageViewModel vmSource = e.Object as FileImageViewModel;
        //                //if (vmSource != null)
        //                //{
        //                //    var item = this.lstGroups.InputHitTest(e.DropPoint);

        //                //    System.Windows.Controls.TextBlock tb = item as System.Windows.Controls.TextBlock;

        //                //    if (tb == null)
        //                //    {
        //                //        var fe = BrainTechLLC.WPF.TempExten.GetAllChildren<TextBlock>(item as FrameworkElement, true);
        //                //        if (fe != null && fe.Count > 0)
        //                //        {
        //                //            tb = fe[0];
        //                //        }
        //                //    }

        //                //    if (tb != null)
        //                //    {
        //                //        GroupViewModel vmDest = tb.Tag as GroupViewModel;

        //                //        if (vmDest != null)
        //                //        {
        //                //            DirectoriesToExamineCollectionViewModel.AddFileImageToGroup(vmSource.FileName, vmDest.GroupName);
        //                //        }
        //                //    }
        //                //}
        //            }
        //        }
        //    }
        //}

        private void txtGroupName_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            System.Windows.Controls.TextBlock tb = sender as System.Windows.Controls.TextBlock;
            GroupViewModel vm = tb.Tag as GroupViewModel;
            HideOrShowFilesInGroup(tb);
        }

        private static void HideOrShowFilesInGroup(FrameworkElement tb)
        {
            ListBoxItem parentItem = BrainTechLLC.WPF.TempExten.FindParent<ListBoxItem>(tb);
            var found = parentItem.GetAllChildren<Grid>(true).FirstOrDefault(o => o.Name == "listOfFiles") as Grid;
            found.Visibility = found.Visibility == System.Windows.Visibility.Collapsed ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void removeFileImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            DirectoryToExamineViewModel vm = img.Tag as DirectoryToExamineViewModel;
            ListBox listbox = BrainTechLLC.WPF.TempExten.FindParent<ListBox>(img);
            var allSelected = listbox.GetSelected<DirectoryToExamineViewModel>();
            if (allSelected.FirstOrDefault(o => o.Directory == vm.Directory) == null)
            {
                allSelected.Add(vm);
            }

            DirectoriesToExamineViewModel dirs = listbox.Tag as DirectoriesToExamineViewModel;            
            allSelected.ForEach(o => dirs.RemoveDir(o.Directory));
        }

        private void lstGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DirectoriesToExamineCollectionViewModel.CurrentlySelectedGroupsInListbox.Count > 0)
            {
                DirectoriesToExamineCollectionViewModel.CurrentlySelectedGroupsInListbox.ForEach(o => o.IsSelected = false);
                DirectoriesToExamineCollectionViewModel.CurrentlySelectedGroupsInListbox.Clear();
                DirectoriesToExamineCollectionViewModel.OnCurrentlySelectedGroupsInListboxChanged();
            }

            if (lstGroups.SelectedItems == null || lstGroups.SelectedItems.Count == 0)
            {
            }
            else
            {
                foreach (DirectoriesToExamineViewModel item in lstGroups.SelectedItems)
                {
                    DirectoriesToExamineCollectionViewModel.CurrentlySelectedGroupsInListbox.Add(item);
                    item.IsSelected = true;
                }
                DirectoriesToExamineCollectionViewModel.OnCurrentlySelectedGroupsInListboxChanged();
            }
        }

        private void mnuDeleteGroup_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            DirectoriesToExamineViewModel vm = item.Tag as DirectoriesToExamineViewModel;
            DeleteGroup(vm);
        }

        private void DeleteGroup(DirectoriesToExamineViewModel vm)
        {
            var result = MessageBox.Show(string.Format("Are you sure you want to permanently remove the group '{0}'?", vm.Name), "Delete?", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                DirectoriesToExamineCollectionViewModel.RemoveGroup(vm);
            }
        }

        public void RemoveDirectory(string directory)
        {
            Dispatcher.BeginInvoke(new VoidDelegate(() =>
            {
                for (int n = 0; n < DirectoriesToExamineCollectionViewModel.Count; n++)
                {
                    var dirs = DirectoriesToExamineCollectionViewModel[n];
                    if (dirs.FirstOrDefault(o => o.Directory == directory) != null)
                    {
                        dirs.RemoveDir(directory);
                    }
                }
            }));
        }

        private void chkSelect_Checked(object sender, RoutedEventArgs e)
        {
            //CheckBox cb = sender as CheckBox;
            //GroupViewModel vm = cb.Tag as GroupViewModel;

            //if (vm != null)
            //{
            //    foreach (GroupViewModel gvm in lstGroups.SelectedItems)
            //    {
            //        gvm.IsSelected = true;
            //    }
            //    vm.IsSelected = true;

            //    if (DirectoriesToExamineCollectionViewModel.ShowOnlySelectedGroups)
            //    {
            //        Settings.Values.RaisePropertyChanged("FileNameFilter");
            //    }
            //}
        }

        private void chkSelect_Unchecked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            DirectoriesToExamineViewModel vm = cb.Tag as DirectoriesToExamineViewModel;

            if (vm != null)
            {
                foreach (DirectoriesToExamineViewModel gvm in lstGroups.SelectedItems)
                {
                    gvm.IsSelected = false;
                }
                vm.IsSelected = false;

                if (DirectoriesToExamineCollectionViewModel.ShowOnlySelectedGroups)
                {
                    Settings.Values.RaisePropertyChanged("FileNameFilter");
                }
            }
        }

        private void btnAddGroup_Checked(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(new VoidDelegate(() =>
            {
                txtNewGroupName.SelectAll();
                txtNewGroupName.Focus();
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        private void btnDelete_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image cb = sender as Image;
            DirectoriesToExamineViewModel vm = cb.Tag as DirectoriesToExamineViewModel;
            DeleteGroup(vm);
        }

        private void btnCloseView_Click(object sender, RoutedEventArgs e)
        {
            Settings.Values.FolderListVisible = false;
        }

        private void btnEdit_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Image item = sender as Image;
            DirectoriesToExamineViewModel vm = item.Tag as DirectoriesToExamineViewModel;
            vm.IsInEditMode = true;            
        }

        private void txtEditGroupName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
            {
                TextBox tb = sender as TextBox;
                DirectoriesToExamineViewModel vm = tb.Tag as DirectoriesToExamineViewModel;
                vm.IsInEditMode = false;
                tb.Clear();
                e.Handled = true;
            }
            else if (e.Key == System.Windows.Input.Key.Enter)
            {
                TextBox tb = sender as TextBox;
                DirectoriesToExamineViewModel vm = tb.Tag as DirectoriesToExamineViewModel;
                vm.Name = tb.Text;
                vm.IsInEditMode = false;
                tb.Clear();
                e.Handled = true;
            }
        }

        private void mnuRename_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            DirectoriesToExamineViewModel vm = item.Tag as DirectoriesToExamineViewModel;
            vm.IsInEditMode = true;            
        }

        private void txtEditGroupName_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb.Visibility == System.Windows.Visibility.Visible)
            {
                tb.Focus();
            }
        }
    }
}
